from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        # 设置只读字段
        read_only_fields = ["id", "username", "is_staff", "is_superuser", "is_active", "last_login", "date_joined"]

    def create(self, validated_data):
        user = super().create(validated_data)

        return user

    def update(self, instance, validated_data):
        # 如果更新请求中包含密码，也需要重新加密
        password = validated_data.pop('password', None)
        if password is not None:
            instance.set_password(password)
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()
        return instance


class UserRegistrySerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

    def create(self, validated_data):
        # 从validated_data中提取密码，使用set_password方法加密
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        return user

    def update(self, instance, validated_data):
        # 如果更新请求中包含密码，也需要重新加密
        password = validated_data.pop('password', None)
        if password is not None:
            instance.set_password(password)
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()
        return instance
